﻿using System;
using System.Collections.Generic;
using System.Drawing;

using Spencen.Mobile.UI;
using Spencen.Mobile.UI.Transitions;
using Spencen.Mobile.UI.Easings;
using Spencen.Mobile.UI.Primitives;
using Spencen.Mobile.UI.Controls;

namespace Spencen.Mobile.UI.Navigation
{
    public class TransitionNavigator : INavigator
    {
        public Stack<View> _views = new Stack<View>();

        private Canvas _hostCanvas;

        public TransitionNavigator( Canvas hostCanvas )
        {
            _hostCanvas = hostCanvas;
        }

        public TimeSpan TransitionDuration { get; set; }
        public IEasingFunction TransitionEasing { get; set; }

        #region INavigator Members

        public View Back()
        {
            if ( _views.Count == 0 )
                return null;
            else
            {
                var oldView = _views.Pop();
                var newView = _views.Peek();

                var transition = new SlideTransition()
                {
                    Duration = TransitionDuration,
                    EasingFunction = TransitionEasing,
                    NewView = newView,
                    OldView = oldView,
                    Offset = new Point( _hostCanvas.Width, 0 )
                };
               
                using ( var graphics = _hostCanvas.CreateGraphics() )
                    transition.Start( new GraphicsContext( graphics ) );

                _hostCanvas.View = newView;
                _hostCanvas.Invalidate();

                _hostCanvas.Menu = newView.MenuBar ?? new MenuBar( _hostCanvas ); // Apply menu after transition

                return newView;
            }
        }

        public void Forward( View newView )
        {
            if ( _views.Count == 0 )
            {
                _hostCanvas.View = newView;
                _hostCanvas.Invalidate();
            }
            else
            {
                var oldView = _views.Peek();

                var transition = new SlideTransition()
                {
                    Duration = TransitionDuration,
                    EasingFunction = TransitionEasing,
                    NewView = newView,
                    OldView = oldView,
                    Offset = new Point( - _hostCanvas.Width, 0 )
                };

                using ( var graphics = _hostCanvas.CreateGraphics() )
                    transition.Start( new GraphicsContext( graphics ) );

                _hostCanvas.View = newView;
                _hostCanvas.Invalidate();
            }
            _views.Push( newView );
        }

        #endregion
    }
}
